package com.lock.chess.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lock.chess.Enums.LevelEnum;
import com.lock.chess.Enums.MessageEnum;
import com.lock.chess.config.RandomNickname;
import com.lock.chess.config.ResponseApi;
import com.lock.chess.controller.WebSocketServer;
import com.lock.chess.dao.PlayerMapper;
import com.lock.chess.dto.PlayerDto;
import com.lock.chess.model.Player;
import com.lock.chess.service.PlayerService;
import com.lock.chess.utils.SendSms;
import com.lock.chess.utils.SocketResponse;
import io.netty.channel.ChannelHandlerContext;
import javax.websocket.Session;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class PlayerServiceImpl implements PlayerService {
    @Resource
    private PlayerMapper playerMapper;
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public void createPlayer(Session session, PlayerDto playerDto) {
        String phone = playerDto.getPhone();
        Player user = playerMapper.selectOne(new QueryWrapper<Player>().eq("phone", phone));
        if (user != null){
            try {
                session.getBasicRemote().sendText(SocketResponse.fail(MessageEnum.REGISTER.getCode(), "账户已存在，请登录"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;
        }
        Player player = new Player();
        player.setPhone(phone);
        Random random = new Random();
        // 生成一个0到40之间的随机整数
        int randomNumber = random.nextInt(41); // 41是上限（不包括41），因为nextInt(n)生成的是0到n-1之间的随机数
        // 格式化为两位数的整数，不足两位前面补0
        String formattedNumber = String.format("%02d", randomNumber);
        player.setAvatarUrl(formattedNumber);
        player.setNickName(RandomNickname.getName());
        System.out.println(player.getNickName());
        player.setLevel(LevelEnum.BING_V);
        player.setLevelName(LevelEnum.BING_V.getName());
        // 生成一个6位长度的随机数
        int id = 100000 + random.nextInt(900000);
        player.setUserCode(id+"");
        playerMapper.insert(player);
        try {
            WebSocketServer.addWebSocketMap(session, player.getUserCode());
            JSONObject entries = new JSONObject(player);
            WebSocketServer.sendMessage(SocketResponse.success(MessageEnum.REGISTER.getCode(), entries), player.getUserCode());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void playerLogin(Session session, String userCode) {
        Player user = playerMapper.selectOne(new QueryWrapper<Player>().eq("user_code", userCode));
        if (user != null){
            try {
                WebSocketServer.addWebSocketMap(session, user.getUserCode());
                JSONObject entries = new JSONObject(user);
                WebSocketServer.sendMessage(SocketResponse.success(MessageEnum.LOGIN.getCode(), entries), user.getUserCode());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            try {
                WebSocketServer.sendMessage(SocketResponse.fail(MessageEnum.LOGIN.getCode(), "用户不存在"), userCode);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void logOn(Session session, PlayerDto playerDto) {
        try {
            String phone = playerDto.getPhone();
            String code = playerDto.getCode();
            String s = (String) redisTemplate.opsForValue().get(phone);
            if (s != null) {
                if (s.equals(code)) {
                    Player user = playerMapper.selectOne(new QueryWrapper<Player>().eq("phone", phone));
                    if (user != null) {
                        WebSocketServer.addWebSocketMap(session, user.getUserCode());
                        JSONObject entries = new JSONObject(user);
                        WebSocketServer.sendMessage(SocketResponse.success(MessageEnum.LOGON.getCode(), entries), user.getUserCode());
                    } else {
                        this.createPlayer(session, playerDto);
                    }
                } else {
                    WebSocketServer.sendMessage(SocketResponse.fail(MessageEnum.LOGON.getCode(), "验证码错误"), session);
                }
            } else {
                WebSocketServer.sendMessage(SocketResponse.fail(MessageEnum.LOGON.getCode(), "验证码错误"), session);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void sendSMS(Session session, String phone) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            sb.append(new Random().nextInt(9));
        }
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set(phone, sb.toString(), 5, TimeUnit.MINUTES);
        try {
            SendSms.send(phone, sb.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
